package com.pokermind.dse.tcp.client.preset;

import java.util.ArrayList;
import java.util.List;

/**
 * 扑克牌编码工具类
 * 
 * 将字符串格式的牌转换为数字编码（用于AI分析）
 * 
 * 编码规则：
 * - 方片(d): 0-12
 * - 梅花(c): 13-25
 * - 红桃(h): 26-38
 * - 黑桃(s): 39-51
 * 
 * 点数: A=0, 2=1, 3=2, ..., K=12
 * 
 * @author PokerMind Team
 */
public class CardEncoder {
    
    /**
     * 将字符串格式的牌转换为数字编码
     * 
     * @param card 牌的字符串表示，如 "As", "Kh", "2d"
     * @return 数字编码 (0-51)
     */
    public static int encode(String card) {
        if (card == null || card.length() != 2) {
            throw new IllegalArgumentException("Invalid card format: " + card);
        }
        
        char rankChar = card.charAt(0);
        char suitChar = card.charAt(1);
        
        // 获取点数值 (0-12)
        int rankValue = getRankValue(rankChar);
        
        // 获取花色基数
        int suitBase = getSuitBase(suitChar);
        
        return suitBase + rankValue;
    }
    
    /**
     * 批量转换牌
     * 
     * @param cards 牌的字符串列表
     * @return 数字编码列表
     */
    public static List<Integer> encodeList(List<String> cards) {
        List<Integer> encoded = new ArrayList<>();
        for (String card : cards) {
            encoded.add(encode(card));
        }
        return encoded;
    }
    
    /**
     * 获取点数值
     */
    private static int getRankValue(char rank) {
        return switch (rank) {
            case 'A' -> 0;
            case '2' -> 1;
            case '3' -> 2;
            case '4' -> 3;
            case '5' -> 4;
            case '6' -> 5;
            case '7' -> 6;
            case '8' -> 7;
            case '9' -> 8;
            case 'T' -> 9;
            case 'J' -> 10;
            case 'Q' -> 11;
            case 'K' -> 12;
            default -> throw new IllegalArgumentException("Invalid rank: " + rank);
        };
    }
    
    /**
     * 获取花色基数
     */
    private static int getSuitBase(char suit) {
        return switch (suit) {
            case 'd' -> 0;   // 方片 0-12
            case 'c' -> 13;  // 梅花 13-25
            case 'h' -> 26;  // 红桃 26-38
            case 's' -> 39;  // 黑桃 39-51
            default -> throw new IllegalArgumentException("Invalid suit: " + suit);
        };
    }
    
    /**
     * 将数字编码转换回字符串（用于调试）
     */
    public static String decode(int cardNumber) {
        if (cardNumber < 0 || cardNumber > 51) {
            throw new IllegalArgumentException("Invalid card number: " + cardNumber);
        }
        
        String[] suits = {"d", "c", "h", "s"};  // 方片、梅花、红桃、黑桃
        String[] ranks = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"};
        
        int suitIndex = cardNumber / 13;
        int rankIndex = cardNumber % 13;
        
        return ranks[rankIndex] + suits[suitIndex];
    }
}

